package com.agent.action.controller;

import com.agent.action.entity.AgentMessageHistoryEntity;
import com.agent.action.param.ChatParam;
import com.agent.action.param.PauseParam;
import com.agent.action.service.AgentService;
import com.agent.action.vo.ChatHistoryVO;
import com.agent.action.vo.ChatVO;
import com.agent.commons.Result.Result;
import com.agent.commons.enums.Agent;
import com.agent.commons.exception.BaseException;
import com.agent.commons.other.MessageHistory;
import com.agent.feign.client.HistoryClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * 智能体交互
 */
@Slf4j
@RestController
@RequestMapping("/agent")
public class AgentController {
    @Resource
    private AgentService agentService;
    @Resource
    private HistoryClient historyClient;

    /**
     * 智能体对话
     * @param chatParam
     * @return
     */
    @PostMapping(value = "/chat",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatVO> chat(@RequestBody ChatParam chatParam){
        if(chatParam.getConversationId()!=null&&!checkConversationIdWithUserId(chatParam)){
            log.error("conversationId校验失败!");
            throw new BaseException(500,"conversationId校验失败!");
        }
        MessageHistory messageHistory = new MessageHistory();
        messageHistory.setUserId(chatParam.getUserId());
        messageHistory.setContent(chatParam.getQuery());
        messageHistory.setRole(Agent.USER);
        messageHistory.setConversationId(chatParam.getConversationId());
        return agentService.chat(chatParam, messageHistory);
    }

    /**
     * 获取会话历史消息
     * @param message
     */
    @PostMapping("/get/history")
    public Result<List<ChatHistoryVO>> getMessageHistory(@RequestBody AgentMessageHistoryEntity message){
        log.info("AgentMessageHistoryEntity:{}",message);
        return Result.success(agentService.getMessageHistory(message));
    }

    /**
     * 暂停智能体响应
     * @param pauseParam
     */
    @PostMapping("/pause")
    public Result<Boolean> pause(@RequestBody PauseParam pauseParam){
        agentService.pause(pauseParam);
        return Result.success(true);
    }


    /**
     * 校验会话id和用户id是否对应
     * @param chatParam
     * @return
     */
    private boolean checkConversationIdWithUserId(ChatParam chatParam){
        return historyClient.checkConversationIdWithUserId(chatParam.getUserId(),chatParam.getConversationId());
    }

}
